package com.ibeeking.found.msg.rest.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaMsgService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaUniformMessage;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.msg.rest.service.IOpenService;
import com.ibeeking.found.msg.rest.service.ISendWxMaMsgService;
import com.ibeeking.found.msg.service.common.vo.WxMaMsgTemplateVO;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SendSmsServiceImpl
 * @Description 发送短信实现类
 * @Author ibeeking
 * @Date 2020-12-10 9:21
 **/
@Service
public class SendWxMaMsgServiceImpl implements ISendWxMaMsgService {

    @Resource
    private IOpenService wxOpenServiceImpl;

    /**
     * 发送微信订阅消息
     *
     * @param maMsgTemplate
     * @param paramMap
     * @param toUserOpenId
     * @return
     */
    @SneakyThrows
    @Override
    public Boolean sendWxMaSubscribeMessage(WxMaMsgTemplateVO maMsgTemplate, Map<String, String> paramMap, String toUserOpenId) {
        if (ObjectUtil.isNull(maMsgTemplate) || CollUtil.isEmpty(paramMap) || StringUtils.isBlank(toUserOpenId)) {
            return false;
        }
        Long tenantId = UserUtils.getTenantID();
        WxMaService wxMaService = wxOpenServiceImpl.getWxOpenMaService(tenantId);
        WxMaMsgService msgService = wxMaService.getMsgService();
        WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
        subscribeMessage.setToUser(toUserOpenId);
        subscribeMessage.setTemplateId(maMsgTemplate.getPriTmplId());
        List<WxMaSubscribeMessage.MsgData> wxMaSubscribeMessageDataList = getWxMaSubscribeMessageDataList(paramMap);
        subscribeMessage.setData(wxMaSubscribeMessageDataList);
        msgService.sendSubscribeMsg(subscribeMessage);
        return true;
    }

    @Override
    public Boolean sendWxMaTemplateMessage(Integer tenantId, String templateCode, List<String> toUser, Map<String, String> paramMap) throws WxErrorException {
        if (StringUtils.isEmpty(templateCode) || CollUtil.isEmpty(paramMap) || Collections3.isEmpty(toUser)) {
            return false;
        }
        LogUtils.info(">>>>>>>>>>>sendWxMpTemplateMessage templateCode:{}",templateCode);
        WxMaService wxMaService = wxOpenServiceImpl.getWxOpenMaService(Long.valueOf(tenantId));
        WxMaMsgService msgService = wxMaService.getMsgService();
        String appid = wxMaService.getWxMaConfig().getAppid();
        LogUtils.info(">>>>>>>>>>>sendWxMpTemplateMessage appid:{}",appid);
        WxMaUniformMessage uniformMessage = new WxMaUniformMessage();
        uniformMessage.setMpTemplateMsg(true);
        uniformMessage.setToUser(toUser.get(0));
        uniformMessage.setAppid(appid);

        uniformMessage.setTemplateId(templateCode);

        List<WxMaTemplateData> data = new ArrayList<>();
        for (Map.Entry<String, String> item : paramMap.entrySet()) {
            WxMaTemplateData itemData = new WxMaTemplateData();
            itemData.setName(item.getKey());
            itemData.setValue(item.getValue());
            data.add(itemData);
        }
        uniformMessage.setData(data);
        LogUtils.info(">>>>>>>>>>>sendWxMpTemplateMessage uniformMessage:{}",JsonUtils.toJsonStr(uniformMessage));
        msgService.sendUniformMsg(uniformMessage);
        return true;
    }

    /**
     * 组装微信订阅信息内容
     *
     * @param paramMap 占位符填充内容
     * @return
     */
    private List<WxMaSubscribeMessage.MsgData> getWxMaSubscribeMessageDataList(Map<String, String> paramMap) {
        if (CollUtil.isEmpty(paramMap)) {
            return Collections.emptyList();
        }
        List<WxMaSubscribeMessage.MsgData> dataList = new ArrayList<>();
        for (Map.Entry<String, String> item : paramMap.entrySet()) {
            String key = item.getKey();
            key = StringUtils.remove(key, ".DATA");
            String fillData = item.getValue();
            if (key.contains("thing")) {
                if (fillData.length() > 20) {
                    //thing.DATA   事物  20个以内字符 可汉字、数字、字母或符号组合
                    fillData = fillData.substring(0, 20);
                }
            } else if (key.contains("number") || key.contains("letter")) {
                // number.DATA  数字  32位以内数字 只能数字，可带小数
                // letter.DATA  字母  32位以内字母 只能字母
                if (fillData.length() > 32) {
                    fillData = fillData.substring(0, 32);
                }
            } else if (key.contains("phrase")) {
                if (fillData.length() > 5) {
                    // phrase.DATA  汉字  5个以内汉字  5个以内纯汉字，例如：配送中
                    fillData = fillData.substring(0, 5);
                }
            }
            WxMaSubscribeMessage.MsgData itemData = new WxMaSubscribeMessage.MsgData(key, fillData);
            dataList.add(itemData);
        }
        return dataList;
    }
}
